package com.example.timerecorder;

import androidx.lifecycle.ViewModelProvider;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import androidx.fragment.app.Fragment;


import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;


public class AddFragment extends Fragment {

    public static final int REQUEST_CODE_ADD_TIME = 1;
    public static final int RESULT_CODE_ADD_TIME = 2;
    public static final int REQUEST_CODE_ADD_TAG = 3;
    public static final int RESULT_CODE_ADD_TAG = 4;
    private AddViewModel mViewModel;

    private static final String TAG = "AddFragment";
    private View view;

    private EditText titleText;
    private EditText detailText;
    private TextView currentTime;
    private ImageView alterTimeImage;
    private TextView currentTag;
    private ImageView alterTagImage;
    private Button saveBtn;

    String currentDateStr;
    String currentTimeStr;
    String currentTagStr;

    public static AddFragment newInstance() {
        return new AddFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.add_fragment, container, false);
        titleText = view.findViewById(R.id.addTitle);
        detailText = view.findViewById(R.id.addDetail);
        currentTime = view.findViewById(R.id.currentTime);
        alterTimeImage = view.findViewById(R.id.alterTimeImage);
        currentTag = view.findViewById(R.id.currentTag);
        alterTagImage = view.findViewById(R.id.alterTagImage);
        saveBtn = view.findViewById(R.id.saveAddBtn);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(AddViewModel.class);
        // TODO: Use the ViewModel

        //获取当前时间，设置初始值
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        currentDateStr = simpleDateFormat.format(date).split(" ")[0];
        currentTimeStr = simpleDateFormat.format(date).split(" ")[1];
        String date_time = currentDateStr + " " +currentTimeStr;
        currentTime.setText(date_time);
        Log.i(TAG, "onActivityCreated: date_time:" + date_time);

        //修改时间，跳转页面
        alterTimeImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //打开新窗口
                Intent selectTime = new Intent(getActivity(), SelectTimeActivity.class);
                selectTime.putExtra("current_date", currentDateStr);
                selectTime.putExtra("current_time", currentTimeStr);
                selectTime.putExtra("flag", "add");
                startActivityForResult(selectTime, REQUEST_CODE_ADD_TIME);
            }
        });

        //添加tag，跳转页面
        alterTagImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //打开新窗口
                Intent selectTag = new Intent(getActivity(), SelectTagActivity.class);
                selectTag.putExtra("current_tag", currentTagStr);
                selectTag.putExtra("flag", "add");
                startActivityForResult(selectTag, REQUEST_CODE_ADD_TAG);
            }
        });

        //保存添加记录，跳转首页
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String date = currentDateStr;
                String time = currentTimeStr;
                String title = titleText.getText().toString();

                if(title.equals("")){
                    //未填写标题——提示
                    Toast.makeText(getActivity(), R.string.unfilledTitleTip, Toast.LENGTH_SHORT).show();
                }
                else {

                    String detail = detailText.getText().toString();
                    String tag = currentTagStr;

                    Item item = new Item(date, time, title, detail, tag);
                    DBManager dbManager = new DBManager(getActivity().getApplicationContext());
                    dbManager.add(item);
                    Log.i("db","新增记录");

                    Intent intent = new Intent(getActivity(),MainActivity.class);
                    startActivity(intent);
                    Log.i(TAG, "onClick: 新增记录，跳转首页");
                    getActivity().finish();

                }

            }
        });

    }


    //接收传过来的时间和tag
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //requestCode是哪个窗口带回来的, resultCode表明窗口带回来的哪个数据
        if(requestCode == REQUEST_CODE_ADD_TIME && resultCode == RESULT_CODE_ADD_TIME){
            //接收修改后时间
            MainActivity mainActivity = (MainActivity) getActivity();
            FragmentManager fragmentManager = mainActivity.getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.commit();

            currentDateStr = data.getStringExtra("select_date");
            currentTimeStr = data.getStringExtra("select_time");
            String date_time = currentDateStr + " " +currentTimeStr;
            currentTime.setText(date_time);
            Log.i(TAG, "onActivityResult: date_time:" + date_time);

        }else if(requestCode == REQUEST_CODE_ADD_TAG && resultCode == RESULT_CODE_ADD_TAG) {
            //接收选择的标签
            MainActivity mainActivity = (MainActivity) getActivity();
            FragmentManager fragmentManager = mainActivity.getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.commit();

            currentTagStr = data.getStringExtra("select_tag");
            currentTag.setText(currentTagStr);
            Log.i(TAG, "onActivityResult: current_tag:" + currentTagStr);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


}